<?php

class AdminProductController extends \BaseController {

	protected $layout = 'admin/layout/default';
	
	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		$published = Input::get('published');
		
		switch ($published) {
			case '0':
				$products = Product::notPublished()->get(); 
				break;
			case '1':
				$products = Product::published()->get();
				break;
			default:
				$products = Product::all();
				break;
		}

		$this->layout->content = View::make('admin.product.index', array('published' => $published, 'products' => $products));
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		$this->layout->content = View::make('admin.product.create');
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		$rules = [
			'name'		=> 'required',
			'published' => 'required|numeric'
		];
		
		$validator = Validator::make(Input::all(), $rules);
		
		if ($validator->fails()) {
			return Redirect::to('admin/product/create')
				->withErrors($validator)
				->withInput();
		} else {
			Product::create(Input::all());
		
			Session::flash('message', 'Successfully created Product!');
			return Redirect::to('admin/product');
		}
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		$product = Product::find($id);

		$this->layout->content = View::make('admin.product.show')->with('product', $product);
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$product = Product::find($id);

		$this->layout->content = View::make('admin.product.edit')->with('product', $product);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$rules = [
			'name'		=> 'required',
			'published' => 'required|numeric'
		];
		
		$validator = Validator::make(Input::all(), $rules);
		
		if ($validator->fails()) {
			return Redirect::to('admin/product/' . $id . '/edit')
				->withErrors($validator)
				->withInput();
		} else {
			$product = Product::find($id);
			$product->update(Input::all());

			Session::flash('message', 'Successfully updated Product!');
			return Redirect::to('admin/product');
		}
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$product = Product::find($id);
		$product->delete();

		Session::flash('message', 'Successfully deleted the Product!');
		return Redirect::to('admin/product');
	}
}